package com.sz.util;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
@PropertySource(value= {"classpath:application.properties"})
public class MybatisCon {

    @Value("${mydriver}")
    private String mydriver;
    @Value("${myurl}")
    private String myurl;
    @Value("${myuser}")
    private String myuser;
    @Value("${mypwd}")
    private String mypwd;

    @Autowired
    private BasicDataSource dataSource;

    @Bean
    public BasicDataSource dataSource() {
        BasicDataSource bs = new BasicDataSource();
        bs.setDriverClassName(mydriver);
        bs.setUrl(myurl);
        bs.setUsername(myuser);
        bs.setPassword(mypwd);
        return bs;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return sqlSessionFactory.getObject();
    }
}
